<?php

	#
	#	Attach config files here. Add additional configs to here
	#

	require 'Configs/Environment.config.php';
	require CONFIG_PATH . 'Controllers.config.php';
	require CONFIG_PATH . 'Session.config.php';
	require CONFIG_PATH . 'Database.config.php';
	
	#
	#	Include classes required to run MVC framework
	#	
	
	require CLASS_PATH . 'Datasources.class.php';
	require CLASS_PATH . 'View.class.php';	
	require CLASS_PATH . 'Controller.class.php';	
	require CLASS_PATH . 'Router.class.php';	
	
	#
	#	Create Datasource Object and connect to databases
	#
	
	$_DATASOURCE = new Datasources();
	$_DATASOURCE->create();
	
	#
	#	Create an instance of the Controller class, and pass it the Route
	#
	
	$_ROUTE = new Router();
	
	$controller = $_ROUTE->controller.'_controller';
	$action = $_ROUTE->action.'_action';
			
	# if the folder (application) is default, and the controller is also 'default', 
	# load "Applications/default/controller/default.controller.php"
	
	$include_path = APPLICATION_PATH.$_ROUTE->folder.'/controller/'.$_ROUTE->controller.'.controller.php';
	
	if(file_exists($include_path))
	{
		# include class
		include $include_path;

		# instantiate class
		$app_controller = new $controller();
		
		function __autoload($class_name) 
		{
			$require_path = APPLICATION_PATH.$_ROUTE->folder.'/model/' . $class_name . '.model.php';
			
			if(!file_exists($require_path))
			{
				$require_path = PLUGIN_PATH . $class_name . '.plugin.php';
			}

			if(!file_exists($require_path))
			{
				return false;
			}
			else
			{
				require_once $require_path;
			}		
		}
		
		# check to see if the desired method exists
		if(method_exists($app_controller, $action))
		{
			if(is_callable(array($app_controller, $action)))
			{		
				# Call the hook to run before the method
				$app_controller->BeforeCall();	
			
				# If the method exists, call it.
				$app_controller->$action();		
				
				# Call the hook to run after the method
				$app_controller->AfterCall();	
				
				# Display the page
				$app_controller->view->Display();
			}
			else
			{
				# the method you wanted exists, but is not callable, so we go to the 403 method.
				$app_controller->fourohthree();
			}
		}
		else
		{
			# the method you wanted didn't exist, so we go to the 404 method.
			$app_controller->fourohfour();
		}
	}
	else
	{
		# the controller you were looking for doesn't exists, therefor we go to the Controller's fourohfour() method	
		$app_controller = new Controller();
		$app_controller->fourohfour();
	}
	
	#
	#	Disconnect from the defined Datasources
	#
	
	$_DATASOURCE->destroy();
	
?>